#include "AT/AT_custom.h"
#include "DataBase/DataBase.h"
#include "OLED_Driver/oled.h"
#include "WIFI/WIFI.h"
#include "cmsis_os2.h"
#include "hi_wifi_api.h"
#include "iot_gpio.h"
#include "iot_uart.h"
#include "ohos_init.h"
#include "wifi_device.h"
#include <hi_io.h>
#include <hi_net_api.h>
#include <stdio.h>

WifiDeviceConfig scan_info[WIFI_SCAN_HOTSPOT_LIMIT];

int telnet_init = 0;

static void *user_task(void *arg)
{
    ip_addr_t ip_addr;
    char str[WIFI_MAX_SSID_LEN];
    OLED_Init();
    OLED_ShowString(0, 0, "WIFI Init ...", 16);
    OLED_flush(1);
    WIFI_Init();
    OLED_ShowString(0, 2, "Connect to WIFI ...", 16);
    OLED_flush(1);
    if (WIFI_Connect() != WIFI_SUCCESS)
    {
        OLED_Clear();
        OLED_ShowString(0, 0, " Connect field", 16);
        OLED_flush(1);
        while (WIFI_isConnected(NULL) == 0)
        {
            sleep(1);
        }
    }

    for (;;)
    {
        if (WIFI_isConnected(&ip_addr))
        {
            if (telnet_init == 0)
            {
                Telnet_init();
                telnet_init = 1;
            }

            if (Telnet_connected())
            {
                OLED_Enable(0);
            }
            else
            {
                OLED_Enable(1);
                OLED_Clear();
                char *ip_str = ipaddr_ntoa(&ip_addr);
                int len = strlen(ip_str);
                OLED_ShowString((16 - len) * 4, 2, ip_str, 16);
                WIFI_getSSID(str, sizeof(str));
                str[17] = 0;
                len = strlen(str);
                OLED_ShowString((16 - len) * 4, 0, str, 16);
            }
        }
        else
        {
            OLED_Enable(1);
            OLED_Clear();
            OLED_ShowString(0, 0, " Connect field", 16);
        }
        OLED_flush(1);
        sleep(1);
    }
}

static void user_entry(void)
{
    IotUartAttribute uart_attr = {0};
    if (db_get_uart_config(&uart_attr) >= 0)
    {
        printf("[UART][init] baud: %d, dataBits: %d, stopBits: %d, parity: %d\r\n", uart_attr.baudRate,
               uart_attr.dataBits, uart_attr.stopBits, uart_attr.parity);
        hi_io_set_pull(HI_IO_NAME_GPIO_11, HI_IO_PULL_UP);
        hi_io_set_pull(HI_IO_NAME_GPIO_12, HI_IO_PULL_UP);
        hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_UART2_TXD);
        hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_UART2_RXD);
        IoTUartInit(2, &uart_attr);
    }

    AT_custom_init();

    osThreadAttr_t attr;

    attr.name = "user_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    printf("hello World\r\n");

    if (osThreadNew((osThreadFunc_t)user_task, NULL, &attr) == NULL)
    {
        printf("[LedExample] Falied to create LedTask!\n");
    }
}

SYS_RUN(user_entry);
